from flask import *
from bluePrints.forms import LoginForm, RegisterForm
from werkzeug.datastructures import MultiDict
from exts import *
from models import animal as Animal
from models import articles as Articles
from sqlalchemy import or_

# 创建一个名为 'search' 的蓝图，URL 前缀为 '/search'
search = Blueprint('search', __name__, url_prefix='/search')

@search.route('/pets/<keyword>')
def search_pets(keyword):
    try:
        # 使用模糊匹配搜索宠物信息
        pets = Animal.query.filter(
            or_(
                Animal.全名.like(f'%{keyword}%'),
                Animal.别名.like(f'%{keyword}%'),
                Animal.分类.like(f'%{keyword}%'),
                Animal.简介.like(f'%{keyword}%')
            )
        ).all()
        
        # 将查询结果转换为字典列表
        result = [{
            'id': pet.id,
            '全名': pet.全名,
            'imgPath': pet.imgPath,
            '分类': pet.分类,
            '简介': pet.简介
        } for pet in pets]
        
        return jsonify({
            'code': 200, 
            'message': '搜索成功', 
            'data': result,

        })
    except Exception as e:
        return jsonify({'code': 500, 'message': str(e)})

@search.route('/articles/<keyword>')
def search_articles(keyword):
    try:
        # 使用模糊匹配搜索文章
        articles = Articles.query.filter(
            or_(
                Articles.title.like(f'%{keyword}%'),
                Articles.contents_json.like(f'%{keyword}%')
            )
        ).all()
        
        # 将查询结果转换为字典列表
        result = [{
            'id': article.id,
            'title': article.title,
            'content': getFirstText(contentUcode(article.contents_json),100),
            'img':getFirstImg(contentUcode(article.contents_json)),
            'date': article.view_date.strftime('%Y-%m-%d %H:%M:%S') if article.view_date else None
        } for article in articles]
        
        return jsonify({
            'code': 200, 
            'message': '搜索成功', 
            'data': result,
        })
    except Exception as e:
        return jsonify({'code': 500, 'message': str(e)})



def contentUcode(contents_json):
    try:
        return json.loads(contents_json)
    except Exception as e:
        print('json解码错误',e)


def getFirstImg(content):
    # print('123',content)
    for item in content:
        if item['type'] == 'img':
            # print(item['url'])
            return item['url'] 
            break
def getFirstText(content,num):
    i=0
    # print('123',content)
    for item in content:
        if item['type'] == 'text' :
            i+=1
            if i>1:
                # print(item['url'])
                text = item['content'] 
                text = f'{text[:num]}...'
                return text
                break